<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="login-container">
    <!-- 添加粒子效果的canvas -->
    <canvas ref="particleCanvas" class="particle-canvas"></canvas>

    <div class="stars-background">
      <div class="constellation"></div>
    </div>
    <div class="login-box">
      <h1 class="welcome-text">登录界面</h1>
      <div class="login-form">
        <div class="input-group">
          <el-input
            v-model="data.form.userName"
            placeholder="请输入账号"
            prefix-icon="User"
            class="custom-input"
          ></el-input>
        </div>
        <div class="input-group">
          <el-input
            v-model="data.form.passWord"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            class="custom-input"
          ></el-input>
        </div>
        <el-button type="primary" class="login-button"  @click="handleLogin">登录</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount ,reactive} from 'vue'
import {useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
import request from "@/utils/request";
import { encryptPassword } from '@/utils/crypto';
import { searchSelfRouter } from '@/api/menu'
import {buildMenuTree} from '@/utils/dynamicRouter'
import Forget from "@/view/components/forget.vue";


const router = useRouter()

const particleCanvas = ref(null)
let animationFrameId= null

const data=reactive({
    form:{
        userName:"",
        passWord:"",
    },
})

const handleLogin = () => {
  // 登录逻辑保持不变
  if (!data.form.userName) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!data.form.passWord) {
    ElMessage.warning('请输入密码')
    return
  }
  console.log('data.form',data.form)
  // 登录
  request.post('/login',{
      userName: data.form.userName,
      passWord: encryptPassword(data.form.passWord)
  }).then(res=>{
        if(res.code==200){
            console.log('res',res)
            // 加密存储用户信息
            // encryptAndStore('code_user', JSON.stringify(res.data||{}))
            localStorage.setItem('code_user',JSON.stringify(res.data||{}))
            localStorage.setItem('role', res.data.owner || '') // 存储当前角色ID
            const currentOwnerId=res.data.owner.split(',')[0] // 取第一个角色ID
            localStorage.setItem('currentOwnerId', currentOwnerId || '') // 存储当前角色ID
            ElMessage.success('登录成功')
            searchSelfRouter().then(res => {
              const rawMenu = res.data
              localStorage.setItem('menuRoutes', JSON.stringify(rawMenu)) // 存起来

              const dynamicRoutes = buildMenuTree(rawMenu)
              dynamicRoutes.forEach(route => {
                router.addRoute(route)
              })
              console.log('跳转前', router.getRoutes())
               // 密码复杂度校验（密码中至少包含字母、数字和特殊字符，长度至少6位）
              const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!@#$%^&*()_+\[\]{};':"\\|,.<>\/?]).{6,}$/
              if (!passwordRegex.test(data.form.passWord)) {
                ElMessage.warning('密码复杂度不够，请及时修改密码！')
                router.replace('/components/forget')
              }else{
                router.replace('/menu')
              }
            }
            ).catch(err => {
              console.error('获取菜单失败', err)
              ElMessage.error('获取菜单失败')
            })


        }else{
            ElMessage.error("账号或密码错误")
        }
    }
    )
}




onMounted(() => {
  initConstellation()
  initParticles() // 初始化粒子效果

  // 监听窗口大小变化，调整canvas尺寸
  window.addEventListener('resize', resizeCanvas)
})

onBeforeUnmount(() => {
  // 清理资源
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
  window.removeEventListener('resize', resizeCanvas)
})

// 初始化星座动画 (保持原有代码)
function initConstellation() {
  // 原有的星座初始化代码保持不变
  const constellation = document.querySelector('.constellation')
  if (!constellation) return

  // 创建星座节点和连线
  const nodeCount = 15
  const nodes = []

  // 创建节点
  for (let i = 0; i < nodeCount; i++) {
    const node = document.createElement('div')
    node.className = 'node'

    const x = Math.random() * 100
    const y = Math.random() * 100

    node.style.left = `${x}%`
    node.style.top = `${y}%`
    node.style.animationDelay = `${Math.random() * 5}s`

    constellation.appendChild(node)
    nodes.push({ element: node, x, y })
  }

  // 创建连线
  for (let i = 0; i < nodeCount; i++) {
    const connections = Math.floor(Math.random() * 3) + 1

    for (let j = 0; j < connections; j++) {
      const targetIndex = Math.floor(Math.random() * nodeCount)
      if (targetIndex !== i) {
        const line = document.createElement('div')
        line.className = 'line'

        const node1 = nodes[i]
        const node2 = nodes[targetIndex]

        const dx = node2.x - node1.x
        const dy = node2.y - node1.y
        const distance = Math.sqrt(dx * dx + dy * dy)
        const angle = Math.atan2(dy, dx) * 180 / Math.PI

        line.style.width = `${distance}vw`
        line.style.left = `${node1.x}%`
        line.style.top = `${node1.y}%`
        line.style.transform = `rotate(${angle}deg)`
        line.style.transformOrigin = '0 0'
        line.style.opacity = `${Math.random() * 0.5 + 0.1}`

        constellation.appendChild(line)
      }
    }
  }
}

// 粒子系统
function initParticles() {
  const canvas = particleCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  const particles = []

  // 设置canvas尺寸
  function resizeCanvas() {
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
  }

  resizeCanvas()

  // 粒子类
  class Particle {
    constructor() {
      this.x = Math.random() * canvas.width
      this.y = Math.random() * canvas.height
      this.size = Math.random() * 2 + 0.5
      this.speedX = Math.random() * 0.5 - 0.25
      this.speedY = Math.random() * 0.5 - 0.25
      this.color = `rgba(255, 255, 255, ${Math.random() * 0.5 + 0.3})`
    }

    // 更新粒子位置
    update() {
      this.x += this.speedX
      this.y += this.speedY

      // 边界检查
      if (this.x < 0 || this.x > canvas.width) {
        this.speedX = -this.speedX
      }

      if (this.y < 0 || this.y > canvas.height) {
        this.speedY = -this.speedY
      }
    }

    // 绘制粒子
    draw() {
      ctx.fillStyle = this.color
      ctx.beginPath()
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
      ctx.fill()
    }
  }

  // 创建粒子
  function createParticles() {
    const particleCount = Math.min(100, Math.floor(canvas.width * canvas.height / 10000))
    for (let i = 0; i < particleCount; i++) {
      particles.push(new Particle())
    }
  }

  // 绘制粒子和连线
  function drawParticles() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    // 绘制粒子
    particles.forEach(particle => {
      particle.update()
      particle.draw()
    })

    // 绘制粒子之间的连线
    for (let i = 0; i < particles.length; i++) {
      for (let j = i + 1; j < particles.length; j++) {
        const dx = particles[i].x - particles[j].x
        const dy = particles[i].y - particles[j].y
        const distance = Math.sqrt(dx * dx + dy * dy)

        // 只连接距离较近的粒子
        if (distance < 100) {
          ctx.beginPath()
          ctx.strokeStyle = `rgba(255, 255, 255, ${0.1 * (1 - distance / 100)})`
          ctx.lineWidth = 0.5
          ctx.moveTo(particles[i].x, particles[i].y)
          ctx.lineTo(particles[j].x, particles[j].y)
          ctx.stroke()
        }
      }
    }

    animationFrameId = requestAnimationFrame(drawParticles)
  }

  createParticles()
  drawParticles()
}

// 窗口大小变化时调整canvas尺寸
function resizeCanvas() {
  if (particleCanvas.value) {
    particleCanvas.value.width = window.innerWidth
    particleCanvas.value.height = window.innerHeight
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

/* 粒子画布样式 */
.particle-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.stars-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #0b1026 0%, #1a2a52 100%);
  z-index: -1;
  overflow: hidden;
}

/* 其他样式保持不变 */
.stars-background::before,
.stars-background::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.stars-background::before {
  background-image:
    radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 4px),
    radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 3px),
    radial-gradient(white, rgba(255,255,255,.1) 2px, transparent 4px);
  background-size: 550px 550px, 350px 350px, 250px 250px;
  background-position: 0 0, 40px 60px, 130px 270px;
  animation: twinkle 10s linear infinite;
}

.stars-background::after {
  background-image:
    radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 2px),
    radial-gradient(white, rgba(255,255,255,.1) 1px, transparent 2px);
  background-size: 400px 400px, 300px 300px;
  background-position: 50px 150px, 200px 300px;
  animation: twinkle 15s linear infinite;
}

/* 星座动画 */
.constellation {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 0;
}

.node {
  position: absolute;
  width: 4px;
  height: 4px;
  background-color: white;
  border-radius: 50%;
  animation: pulse 3s ease-in-out infinite;
}

.line {
  position: absolute;
  height: 1px;
  background: linear-gradient(to right, rgba(255,255,255,0.1), rgba(255,255,255,0.5), rgba(255,255,255,0.1));
  animation: fadeInOut 8s ease-in-out infinite;
}

.login-box {
  width: 400px;
  padding: 20px 0;
  border-radius: 8px;
  background-color: transparent;
  z-index: 2; /* 提高z-index确保在粒子上方 */
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 其余样式保持不变 */
.welcome-text {
  color: #fff;
  text-align: center;
  margin-bottom: 30px;
  font-size: 20px;
  font-weight: normal;
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
  letter-spacing: 1px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 80%;
}

.input-group .custom-input {
  border-radius: 50px;
  overflow: hidden;
}

.input-group :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1);
  border: none;
  box-shadow: none;
  padding: 0 15px;
  height: 45px;
  border-radius: 50px;
}

.input-group :deep(.el-input__inner) {
  color: #fff;
  height: 45px;
}

.input-group :deep(.el-input__prefix-icon) {
  color: rgba(255, 255, 255, 0.7);
}

.login-button {
  height: 45px;
  font-size: 16px;
  background: #1e88e5;
  border: none;
  margin-top: 10px;
  border-radius: 50px;
  transition: all 0.3s ease;
}

.login-button:hover {
  background: #1976d2;
  box-shadow: 0 0 15px rgba(33, 150, 243, 0.5);
}

@keyframes twinkle {
  0% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.5;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 0.8;
  }
  50% {
    transform: scale(1.5);
    opacity: 1;
  }
  100% {
    transform: scale(1);
    opacity: 0.8;
  }
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0.1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 树木剪影 */
.login-container::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20vh;

  background-size: cover;
  background-position: bottom center;
  z-index: 1;
}
</style>
